//
//  VcardTableViewController.m
//  ICup
//
//  Created by liao Echo on 14-10-12.
//  Copyright (c) 2014年 Echo. All rights reserved.
//

#import "VcardTableViewController.h"
#import "AppDelegate.h"
#import "singlePeripheral.h"

#define heightForRowAtIndexPath_height 50


@implementation UIImage (UIImageCategory)

-(UIImage*)scaleToSize:(CGSize)size {
    NSLog(@"category scalesToSize");
    //确定需要保留的区域
    if (size.width>=self.size.width && size.height>=self.size.height) {
        return self;
    }
    
    CGRect rect;
    CGSize imageSize = self.size;
    
    
    
    BOOL fill=YES;
    if (fill) {
        if (imageSize.height > imageSize.width) {
            NSLog(@"if");
            imageSize.width = floor((imageSize.width/imageSize.height) * size.height);
            imageSize.height = size.height;
        } else {
            NSLog(@"else");
            imageSize.height = floor((imageSize.height/imageSize.width) * size.width);
            imageSize.width = size.width;
        }
        rect=CGRectMake(0 + floor(size.width/2 - imageSize.width/2),
                        0 + floor(size.height/2 - imageSize.height/2),
                        imageSize.width, imageSize.height);
    } else  {
        if (imageSize.height < imageSize.width) {
            imageSize.height = floor((imageSize.height/imageSize.width) * size.width);
            imageSize.width = size.width;
        } else {
            imageSize.width = floor((imageSize.width/imageSize.height) * size.height);
            imageSize.height = size.height;
        }
        rect=CGRectMake(0 + floor(rect.size.width/2 - imageSize.width/2),
                        0 + floor(rect.size.height/2 - imageSize.height/2),
                        imageSize.width, imageSize.height);
    }
    
    NSLog(@"rect:%@",NSStringFromCGRect(rect));
    //裁剪缩放
    CGRect drawRect=CGRectMake(0, 0, rect.size.width, rect.size.height);
    UIGraphicsBeginImageContext(drawRect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    //CGContextSaveGState(context);
    CGContextAddRect(context, drawRect);
    //CGContextClip(context);
    
    [self drawInRect:drawRect];
    //CGContextRestoreGState(context);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return newImage;
}
@end


@interface VcardTableViewController ()

@end

@implementation VcardTableViewController
@synthesize birthday,_image ,curSelectString;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)dealloc{
    if (!isLeftBarButtonItemNull) {
        [singlePeripheral calWaiterNum];
    }
}
- (void)setLeftBarButtonItemNull{
    isLeftBarButtonItemNull = YES;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"个人信息";
    if (isLeftBarButtonItemNull) {
        self.navigationItem.leftBarButtonItem = nil;
        self.title = @"填写个人信息";
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:STR(@"下一步") style:UIBarButtonItemStylePlain target:self action:@selector(off_right)];
    }
}
-(void)off_right{
    NSString *msg = nil;
    if (![UD objectForKey:ICUP_CHANGE_SEX]) {
        msg = @"请填写性别";
    }else if (![UD objectForKey:ICUP_CHANGE_BIR]) {
        msg = @"请填写生日";
    }
    else if (![UD objectForKey:ICUP_CHANGE_GAO]) {
        msg = @"请填写升高";
    }else if (![UD objectForKey:ICUP_CHANGE_WEIGHT]) {
        msg = @"请填写体重";
    }else if (![UD objectForKey:ICUP_CHANGE_ADDR]) {
        msg = @"请填写使用场合";
    }else if (![UD objectForKey:ICUP_CHANGE_TIZHI]) {
        msg = @"请填写体质";
    }
    if ([UD objectForKey:FINISHED_VCARD]) {
        [[AppDelegate instance] enterMainUI];
    }else{
        if (msg) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }else{
            [UD setBool:YES forKey:FINISHED_VCARD];
            [UD synchronize];
            [[AppDelegate instance] enterMainUI];
        }
    }
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(CGFloat)tableView:(UITableView *)aTableView heightForHeaderInSection:(NSInteger)section {
    return 20;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    int section = indexPath.section;
    if (section == 0) {
        return 80;
    }else{
        return heightForRowAtIndexPath_height;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    int num = 0;
    if (section == 0) {
        num = 1;
    }else if (section == 1) {
        num= 6;
    }
    return  num;
}
-(void)AdViewPressed{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"图片选择" delegate:self cancelButtonTitle:STR(@"取消") destructiveButtonTitle:nil otherButtonTitles:STR(@"拍照"), STR(@"从手机相册选择"), nil];
    [sheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    UIImagePickerController *imagepickerController = nil;
    if (buttonIndex == 0) {
        imagepickerController = [[UIImagePickerController alloc] init];
        imagepickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    }else if (buttonIndex == 1) {
        imagepickerController = [[UIImagePickerController alloc] init];
        imagepickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    if (imagepickerController) {
        imagepickerController.allowsEditing = NO;
        imagepickerController.delegate = self;
        [self presentViewController:imagepickerController animated:YES completion:^{
            
        }];
    }
}
- (void)imagePickerController:(UIImagePickerController *)apicker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];//
    self._image = [image scaleToSize:CGSizeMake(160, 160)];
    [apicker dismissViewControllerAnimated:YES completion:^{
        [tableView reloadData];
        
        NSData *uploadImageData = UIImageJPEGRepresentation(self._image, 0.6f);
        
        [uploadImageData writeToFile:[RecInfo storePathWithFileName:ICUP_AVATAR] atomically:YES];
        
        [NC postNotificationName:ICUP_CHANGE_AVATAR object:nil];
    }
     ];
}
- (UITableViewCell *)tableView:(UITableView *)tableview cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIdentifier = @"SettingBaseCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    cell.backgroundColor = [UIColor clearColor];//ios7必须要这样处理，不然默认会是白色
    
    if (indexPath.section == 0) {
        UIButton *AdView = [[UIButton alloc] initWithFrame:RECT(5, 5, 70, 70)];
        if (self._image) {
            [AdView setBackgroundImage:self._image forState:UIControlStateNormal];
        }else{
            NSString *path = [RecInfo storePathWithFileName:ICUP_AVATAR];
            if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                UIImage *image = [UIImage imageWithContentsOfFile:path];
                [AdView setBackgroundImage:image forState:UIControlStateNormal];
            }else{
                [AdView setBackgroundImage:IMG(@"头像--图标.png") forState:UIControlStateNormal];
            }
        }
        [AdView addTarget:self action:@selector(AdViewPressed) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:AdView];
        
        for (int i=0; i<2; i++) {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(FX(AdView)+FW(AdView)+8, FY(AdView)+12+i*25, 180, 20)];
            if (i == 0) {
                label.textColor = [UIColor blackColor];
//                label.text = @"海电";
            }else {
                label.textColor = [UIColor grayColor];
//                label.text = @"yok@163.com";
            }
            label.font = [UIFont systemFontOfSize:16];
            label.backgroundColor = [UIColor clearColor];
            [cell addSubview:label];
        }
    }else if(indexPath.section == 1){
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-50, heightForRowAtIndexPath_height)];
        label.textAlignment = UITextAlignmentRight;
        label.textColor = [UIColor blackColor];
        
        label.font = [UIFont systemFontOfSize:18];
        label.backgroundColor = [UIColor clearColor];
        [cell addSubview:label];
        
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.textColor = [UIColor grayColor];
        if (indexPath.row == 0) {
            cell.textLabel.text = @"性别";
//            label.text = @"男";
            if ([UD objectForKey:ICUP_CHANGE_SEX]) {
                label.text = [UD objectForKey:ICUP_CHANGE_SEX];
            }
        }else if (indexPath.row == 1){
            cell.textLabel.text = @"生日";
//            label.text = @"1992-08-09";
            if ([birthday length] > 0) {
                label.text = birthday;
            }
            if ([UD objectForKey:ICUP_CHANGE_BIR]) {
                label.text = [UD objectForKey:ICUP_CHANGE_BIR];
            }
        }else if (indexPath.row == 2){
            cell.textLabel.text = @"身高";
//            label.text = @"166cm";
            if ([UD objectForKey:ICUP_CHANGE_GAO]) {
                label.text = [NSString stringWithFormat:@"%@cm", [UD objectForKey:ICUP_CHANGE_GAO]];
            }
        }else if (indexPath.row == 3){
            cell.textLabel.text = @"体重";
//            label.text = @"50kg";
            if ([UD objectForKey:ICUP_CHANGE_WEIGHT]) {
                label.text = [NSString stringWithFormat:@"%@kg", [UD objectForKey:ICUP_CHANGE_WEIGHT]];
            }
        }else if (indexPath.row == 4){
            cell.textLabel.text = @"使用场合";
//            label.text = @"办公室";
            if ([UD objectForKey:ICUP_CHANGE_ADDR]) {
                label.text = [UD objectForKey:ICUP_CHANGE_ADDR];
            }
        }else if (indexPath.row == 5){
            cell.textLabel.text = @"体质";
//            label.text = @"易出汗";
            if ([UD objectForKey:ICUP_CHANGE_TIZHI]) {
                label.text = [UD objectForKey:ICUP_CHANGE_TIZHI];
            }
        }
    }
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)atableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [atableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section ==0) {
        
    }else  if (indexPath.section ==1) {
        indexPathRow = indexPath.row;
        
        [self initPicker];
    }
}
-(void)setApicker{
    NSDateFormatter *fm=[[NSDateFormatter alloc] init];
    [fm setDateFormat:@"yyyy-MM-dd"];
    NSString *result = [fm stringFromDate:datePicker.date];
    self.birthday = result;
    
    [UD setObject:result forKey:ICUP_CHANGE_BIR];
    [UD synchronize];
    
    [tableView reloadData];
}
#pragma -
-(void)onDatePickerValueChanged:(UIDatePicker*)Apicker {
    [self setApicker];
}
-(void)initPicker{
    if (indexPathRow == 1) {
        
        
        btnbg = [[UIButton alloc] initWithFrame:self.view.bounds];
        btnbg.backgroundColor = RGB(0, 0, 0, .4);
        [self.view addSubview:btnbg];
        
        datePicker=[UIDatePicker new];
        datePicker.backgroundColor = [UIColor grayColor];
        [datePicker setDatePickerMode:UIDatePickerModeDate];
        [datePicker addTarget:self action:@selector(onDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
//        [datePicker setMinimumDate:[NSDate dateWithTimeIntervalSince1970:-1830409580.0]];/*1912*/
//        [datePicker setMaximumDate:[NSDate dateWithTimeIntervalSince1970:820339201.0]];/*1995*/
        datePicker.frame=CGRectMake(0, self.view.bounds.size.height-datePicker.frame.size.height, datePicker.frame.size.width, datePicker.frame.size.height);
        [btnbg addSubview:datePicker];
        
        bgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, FY(datePicker)-44, SCREEN_WIDTH, 44)];
        bgview.userInteractionEnabled = YES;
        bgview.image = [UIImage imageNamed:@"popping_bg.png"];
        [btnbg addSubview:bgview];
        
        UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake(266, 5, 53, 33)];
        [btn setImage:IMG(@"打钩 符号.png") forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:13];
        [btn addTarget:self action:@selector(pickStatureDidFinish) forControlEvents:UIControlEventTouchUpInside];
        [btn setBackgroundImage:[UIImage imageNamed:@"popping_button.png"] forState:UIControlStateNormal];
        [bgview addSubview:btn];
        
        btn = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 53, 33)];
        [btn setImage:IMG(@"X 符号.png") forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:13];
        [btn addTarget:self action:@selector(pickStatureDidCancel) forControlEvents:UIControlEventTouchUpInside];
        [btn setBackgroundImage:[UIImage imageNamed:@"popping_button.png"] forState:UIControlStateNormal];
        [bgview addSubview:btn];
        
        return;
    }
    btnbg = [[UIButton alloc] initWithFrame:self.view.bounds];
    btnbg.backgroundColor = RGB(0, 0, 0, .4);
    [self.view addSubview:btnbg];
    
    picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, FH(btnbg)-150, 0, 150)];
    if (IOS7_OR_LATER) {
        picker.backgroundColor = [UIColor grayColor];
    }
    picker.delegate = self;
    picker.dataSource = self;
    picker.showsSelectionIndicator = YES;
    [btnbg addSubview:picker];
    
    CGFloat bgviewY= FY(picker)-44;
    bgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, bgviewY, SCREEN_WIDTH, 44)];
    bgview.userInteractionEnabled = YES;
    bgview.image = [UIImage imageNamed:@"popping_bg.png"];
    
    UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake(266, 5, 53, 33)];
    [btn setImage:IMG(@"打钩 符号.png") forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    [btn addTarget:self action:@selector(pickStatureDidFinish) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundImage:[UIImage imageNamed:@"popping_button.png"] forState:UIControlStateNormal];
    [bgview addSubview:btn];
    
    btn = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 53, 33)];
    [btn setImage:IMG(@"X 符号.png") forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    [btn addTarget:self action:@selector(pickStatureDidCancel) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundImage:[UIImage imageNamed:@"popping_button.png"] forState:UIControlStateNormal];
    [bgview addSubview:btn];
    
    [btnbg addSubview:bgview];
    
    [picker selectRow:0 inComponent:0 animated:NO];
    
}
-(void)pickStatureDidCancel{
    
    [btnbg removeFromSuperview]; btnbg = nil;
    self.curSelectString = nil;
    datePicker = nil;
}
-(void)pickStatureDidFinish{
    
    [btnbg removeFromSuperview]; btnbg = nil;
    
    if (datePicker) {
        [self setApicker];
    }
    
    [self setView];
    
    self.curSelectString = nil;
    datePicker = nil;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (indexPathRow ==0) {
        if (component == 0) {
            return 2;
        }
    }else  if (indexPathRow ==1) {
        
    }else  if (indexPathRow ==2) {//身高
        if (component == 0) {
            return 120;
        }
    }else  if (indexPathRow ==3) {//体重
        if (component == 0) {
            return 170;
        }
    }else  if (indexPathRow ==4) {
        if (component == 0) {
            return 3;
        }
    }else  if (indexPathRow ==5) {
        if (component == 0) {
            return 3;
        }
    }
    return 6;
}
//第一
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    if (indexPathRow ==0) {
        return 1;
    }else  if (indexPathRow ==1) {
        
    }else  if (indexPathRow ==2) {//身高
        return 1;
    }else  if (indexPathRow ==3) {//体重
        return 1;
    }else  if (indexPathRow ==4) {
        return 1;
    }else  if (indexPathRow ==5) {
        return 1;
    }
    return 1;
}

#pragma UIPickerView Delegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)componen{
    if (indexPathRow ==0) {
        if (row == 0) {
            self.curSelectString = @"男";
            return @"男";
        }else{
            self.curSelectString = @"女";
            return @"女";
        }
    }else  if (indexPathRow ==1) {
        
    }else  if (indexPathRow == 2) {
        self.curSelectString = [NSString stringWithFormat:@"%d", 120+row];
        return [NSString stringWithFormat:@"%d", 120+row];
    }else  if (indexPathRow ==3) {
        self.curSelectString = [NSString stringWithFormat:@"%d", 10+row];
        return [NSString stringWithFormat:@"%d", 10+row];
    }else  if (indexPathRow ==4) {
        if (row == 0) {
            self.curSelectString = @"办公室";
            return @"办公室";
        }else if (row == 1) {
            self.curSelectString = @"家里";
            return @"家里";
        }else{
            self.curSelectString = @"户外";
            return @"户外";
        }
    }else  if (indexPathRow ==5) {
        if (row == 0) {
            self.curSelectString = @"易出汗";
            return @"易出汗";
        }else if (row == 1) {
            self.curSelectString = @"少出汗";
            return @"少出汗";
        }else{
            self.curSelectString = @"正常";
            return @"正常";
        }
    }
    return nil;
}
- (void)pickerView:(UIPickerView *)ApickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    NSString *str = [self pickerView:ApickerView titleForRow:row forComponent:component];
    self.curSelectString = str;
}
-(void)setView{
    if (indexPathRow ==0) {
        if (self.curSelectString) {
            [UD setObject:self.curSelectString forKey:ICUP_CHANGE_SEX];
            [UD synchronize];
        }
    }else  if (indexPathRow ==1) {
        //生日
        
    }else  if (indexPathRow == 2) {
        
        if (self.curSelectString) {
            [UD setObject:self.curSelectString forKey:ICUP_CHANGE_GAO];
            [UD synchronize];
        }
        
    }else  if (indexPathRow ==3) {
        if (self.curSelectString) {
            [UD setObject:self.curSelectString forKey:ICUP_CHANGE_WEIGHT];
            [UD synchronize];
        }
    }else  if (indexPathRow ==4) {
        if (self.curSelectString) {
            [UD setObject:self.curSelectString forKey:ICUP_CHANGE_ADDR];
            [UD synchronize];
        }
    }else  if (indexPathRow ==5) {
        
        if (self.curSelectString) {
            [UD setObject:self.curSelectString forKey:ICUP_CHANGE_TIZHI];
            [UD synchronize];
        }
    }
    [tableView reloadData];
}
@end




